# for循环

for (i in 1:5) {  
  print(i)  
}

fruits <- c("apple", "banana", "cherry")  
for (fruit in fruits) {  
  print(fruit)  
}

# while 循环

sum <- 0  # 初始化求和变量  
i <- 1    # 初始化计数器  

while (i <= 10) {  
  sum <- sum + i   # 将当前计数器值加到求和变量上  
  i <- i + 1       # 更新计数器  
}  

print(sum)  # 输出结果：55

# if-else

num <- 15  

if (num > 10) {  
  print("The number is greater than 10.")  
} else {  
  print("The number is not greater than 10.")  
}


num <- 5  

if (num > 10) {  
  print("The number is greater than 10.")  
} else if (num > 5) {  
  print("The number is greater than 5 but not greater than 10.")  
} else {  
  print("The number is not greater than 5.")  
}

# ifelse
numbers <- c(5, 15, 8, 20, 12)  
result <- ifelse(numbers > 10, "大于10", "不大于10")  
print(result)


# ------------------------------------------
# 准备工作
# ------------------------------------------

setwd("/Users/eimei/Documents/Rdata/")  # 设定工作空间
data <- read.csv("HRdata.csv")  # 读取数据

newdata <- data[c("EmployeeNumber", "Age", "Department", "Attrition", "Education",
                  "EnvironmentSatisfaction", "JobSatisfaction",
                  "MonthlyIncome", "RelationshipSatisfaction")]

temp <- newdata[1:10, ]

# ------------------------------------------
# 任务一
# ------------------------------------------

for (i in names(temp)) print(i)

# ------------------------------------------
# 任务二
# ------------------------------------------

i <- 1

while (i <= length(names(temp))) {
  print(names(temp)[i])
  i <- i + 1
}

# ------------------------------------------
# 任务三
# ------------------------------------------

if(!is.factor(temp$Department)) temp$Department <- as.factor(temp$Department) else print("已经是因子型")

if(!is.factor(temp$Department)) {
  temp$Department <- as.factor(temp$Department)} else {
  print("已经是因子型")
  }

# 与 [ ] 不同，[[ ]] 用于提取数据框的单列时，会返回该列作为向量，而不是数据框的子集。
temp[1]
temp["EmployeeNumber"]
class(temp["EmployeeNumber"])

temp[[1]]
temp[["EmployeeNumber"]]
class(temp[["EmployeeNumber"]])


for(i in names(temp)){
  if(is.character(temp[[i]])) {
    temp[[i]] <- as.factor(temp[[i]])
    cat(i, "已经转换为因子型\n")
    } else {
    cat(i, "的类型是", class(temp[[i]]), "\n")
    }
}

# ------------------------------------------
# 任务四
# ------------------------------------------
ifelse(temp$Age > 35, "大于35", "未超过 35")